package com.gnerv.plug.maven.action;

import com.gnerv.plug.commom.FreeMarkerUtils;
import com.gnerv.plug.maven.model.DependencyInfo;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DependencyVersionAction extends AnAction {

    private static final Pattern PATTERN = Pattern.compile("<dependencies>");
    private static final Pattern PATTERN_PROJECT = Pattern.compile("</project>");

    private Map<String, String> dependency;

    public DependencyVersionAction(){

    }

    public DependencyVersionAction(Map<String, String> dependency, Icon icon) {
        super(dependency.get("version"), dependency.get("artifactId"), icon);
        this.dependency = dependency;
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {
        final Editor editor = event.getRequiredData(CommonDataKeys.EDITOR);
        final Project project = event.getRequiredData(CommonDataKeys.PROJECT);
        final Document document = editor.getDocument();
        String description = FreeMarkerUtils.getContent("MavenPom.ftl", dependency);
        Matcher matcher = PATTERN.matcher(document.getText());
        if (matcher.find()) {
            int start = matcher.start();
            WriteCommandAction.runWriteCommandAction(project, () ->
                    document.insertString(start + 14, description)
            );
        }
    }
}
